package com.example.ocridentification.service;

import com.example.ocridentification.config.ImageToBase64;
import com.example.ocridentification.model.ImageBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class OwnershipService {
    @Autowired
    private OkHttpClient okHttpClient;
    @Autowired
    private ObjectMapper objectMapper;

    private String appcode = "c8518f45d5334300b73c638e299820ab";

    public String getData(byte[] imageBody) {
        String ret = "";
        try {
            // 1. 准备请求体
            ImageBody body = new ImageBody();
            body.setImg(ImageToBase64.imageToBase64(imageBody));

            // 2. 确保APPCODE正确

            // 3. 创建请求
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            String jsonBody = objectMapper.writeValueAsString(body);

            Request request = new Request.Builder()
                    .url("https://bdcqz.market.alicloudapi.com/ocrservice/estateCert")
                    .post(RequestBody.create(jsonBody, JSON))
                    .addHeader("Authorization", "APPCODE " + appcode)
                    .addHeader("Content-Type", "application/json; charset=UTF-8")
                    .build();

            // 4. 执行请求并处理响应
            try (Response response = okHttpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    String errorBody = response.body().string();
                    throw new IOException(
                            "API请求失败:\n" +
                                    "状态码: " + response.code() + "\n" +
                                    "错误信息: " + response.message() + "\n" +
                                    "响应体: " + errorBody
                    );
                }

                ret = response.body().string();
                System.out.println("识别结果: " + ret);
            }
        } catch (Exception e) {
            System.err.println("发生错误: " + e.getMessage());
            e.printStackTrace();
        }
        return ret;
    }
}
